package com.example.littleken.listadapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;
import java.util.Map;

import static com.example.littleken.listadapter.R.id.size;

/**
 * Created by littleken on 2018/4/20.
 */
//自定义adapter
public class MyAdapter extends BaseAdapter{

    List<Map<String,Object>>list;//用于存放源数据
    LayoutInflater inflater;//反射器

    public MyAdapter(Context context) {//构造函数
        this.inflater = LayoutInflater.from(context);//初始化反射器
    }

    public void setList(List<Map<String, Object>> list) {//List set 方法
        this.list = list;
    }

    public int getCount() {//获取有多少个数据源（多少行）
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;//声明voiwholder

        if(convertView == null){
            convertView = inflater.inflate(R.layout.listview_layout,null);//ListView一级优化操作
            holder = new ViewHolder();
            holder.logo = (ImageView) convertView.findViewById(R.id.logo);//ListView二级优化操作
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.version = (TextView) convertView.findViewById(R.id.version);
            holder.size = (TextView) convertView.findViewById(size);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        //View view = inflater.inflate(R.layout.listview_layout,null);//把每行的xml布局文件反射成View对象
        /*ImageView logo = (ImageView) convertView.findViewById(R.id.logo);//拿到需要适配的4个对象
        TextView title = (TextView) convertView.findViewById(R.id.title);
        TextView version = (TextView) convertView.findViewById(R.id.version);
        TextView size = (TextView) convertView.findViewById(R.id.size);*/

        Map map = list.get(position);//为了获取资源id
        holder.logo.setImageResource((Integer) map.get("logo"));//设置每一个需要匹配的对象
        holder.title.setText((String) map.get("title"));
        holder. version.setText((String) map.get("version"));
        holder.size.setText((String) map.get("size"));
        return convertView;
    }

    public class ViewHolder{//ListView二级优化操作
        ImageView logo;//跟需要控件一致
        TextView title;
        TextView version;
        TextView size;
    }
}
